<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="计划编号" prop="planCode">
        <el-input
          v-model="queryParams.planCode"
          placeholder="请输入计划编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计划名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入计划名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备" prop="equipmentId">
        <el-select v-model="queryParams.equipmentId" placeholder="请选择设备" clearable>
          <el-option
            v-for="equipment in equipmentOptions"
            :key="equipment.equipmentId"
            :label="equipment.equipmentName"
            :value="equipment.equipmentId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="planStatus">
        <el-select v-model="queryParams.planStatus" placeholder="请选择状态" clearable>
          <el-option label="启用" value="1" />
          <el-option label="停用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sb:plan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sb:plan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sb:plan:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sb:plan:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="计划编号" align="center" prop="planCode" />
      <el-table-column label="计划名称" align="center" prop="planName" />
      <el-table-column label="设备名称" align="center" prop="equipmentName" />
      <el-table-column label="保养配置" align="center" prop="configName" />
      <el-table-column label="保养人员" align="center" prop="maintainerName" />
      <el-table-column label="负责部门" align="center" prop="deptName" />
      <el-table-column label="周期类型" align="center" prop="cycleType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cycle_type" :value="scope.row.cycleType"/>
        </template>
      </el-table-column>
      <el-table-column label="下次保养日期" align="center" prop="nextMaintenanceDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.nextMaintenanceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="planStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.common_status" :value="scope.row.planStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sb:plan:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sb:plan:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleGenerateRecord(scope.row)"
            v-hasPermi="['sb:plan:generate']"
          >生成记录</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改保养计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划编号" prop="planCode">
              <el-input v-model="form.planCode" placeholder="请输入计划编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="form.planName" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备" prop="equipmentId">
              <el-select v-model="form.equipmentId" placeholder="请选择设备" @change="handleEquipmentChange">
                <el-option
                  v-for="equipment in equipmentOptions"
                  :key="equipment.equipmentId"
                  :label="equipment.equipmentName"
                  :value="equipment.equipmentId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保养配置" prop="configId">
              <el-select v-model="form.configId" placeholder="请选择保养配置" @change="handleConfigChange">
                <el-option
                  v-for="config in configOptions"
                  :key="config.configId"
                  :label="config.configName"
                  :value="config.configId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="保养人员" prop="maintainerId">
              <el-select v-model="form.maintainerId" placeholder="请选择保养人员" @change="handleMaintainerChange">
                <el-option
                  v-for="user in userOptions"
                  :key="user.userId"
                  :label="user.userName"
                  :value="user.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责部门" prop="deptId">
              <el-select v-model="form.deptId" placeholder="请选择负责部门" @change="handleDeptChange">
                <el-option
                  v-for="dept in deptOptions"
                  :key="dept.deptId"
                  :label="dept.deptName"
                  :value="dept.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="周期类型" prop="cycleType">
              <el-select v-model="form.cycleType" placeholder="请选择周期类型">
                <el-option label="每天" value="1" />
                <el-option label="每周" value="2" />
                <el-option label="每月" value="3" />
                <el-option label="每季度" value="4" />
                <el-option label="每年" value="5" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自动生成" prop="autoGenerate">
              <el-radio-group v-model="form.autoGenerate">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker clearable
                v-model="form.startDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择开始日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker clearable
                v-model="form.endDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaintenancePlan, getMaintenancePlan, addMaintenancePlan, updateMaintenancePlan, deleteMaintenancePlan, updateMaintenancePlanStatus, generateMaintenanceRecord, generatePlanCode, checkPlanCodeUnique } from "@/api/sb/maintenancePlan";
import { listEquipment } from "@/api/sb/equipment";
import { listMaintenanceConfig } from "@/api/sb/maintenanceConfig";
import { listUser } from "@/api/system/user";
import { listDept } from "@/api/system/dept";

export default {
  name: "MaintenancePlan",
  dicts: ['common_status', 'cycle_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 保养计划表格数据
      planList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 保养配置选项
      configOptions: [],
      // 设备选项
      equipmentOptions: [],
      // 用户选项
      userOptions: [],
      // 部门选项
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planCode: null,
        planName: null,
        equipmentId: null,
        planStatus: null,
        beginTime: null,
        endTime: null
      },
      // 表单参数
      form: {
        planId: null,
        planCode: "",
        planName: null,
        configId: null,
        configName: null,
        equipmentId: null,
        equipmentName: null,
        cycleType: "1",
        cycleValue: 1,
        cycleConfigJson: "", // 新增存储JSON配置的字段
        startDate: null,
        endDate: null,
        maintainerId: null,
        maintainerName: null,
        planStatus: "1",
        autoGenerate: "1",
        deptId: null,
        deptName: null,
        remark: null
      },
      // 表单校验
      rules: {
        planCode: [
          { required: true, message: "计划编号不能为空", trigger: "blur" }
        ],
        planName: [
          { required: true, message: "计划名称不能为空", trigger: "blur" }
        ],
        equipmentId: [
          { required: true, message: "设备不能为空", trigger: "change" }
        ],
        configId: [
          { required: true, message: "保养配置不能为空", trigger: "change" }
        ],
        maintainerId: [
          { required: true, message: "保养人员不能为空", trigger: "change" }
        ],
        deptId: [
          { required: true, message: "负责部门不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getEquipmentOptions();
    this.getConfigOptions();
    this.getUserOptions();
    this.getDeptOptions();
  },
  methods: {
    /** 查询保养计划列表 */
    getList() {
      this.loading = true;
      listMaintenancePlan(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取设备选项
    getEquipmentOptions() {
      listEquipment({pageSize: 100, pageNum: 1}).then(response => {
        this.equipmentOptions = response.rows;
      });
    },
    // 获取保养配置选项
    getConfigOptions() {
      listMaintenanceConfig().then(response => {
        this.configOptions = response.rows;
      });
    },
    // 获取用户选项
    getUserOptions() {
      listUser().then(response => {
        this.userOptions = response.rows;
      });
    },
    // 获取部门选项
    getDeptOptions() {
      listDept().then(response => {
        this.deptOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        planId: null,
        planCode: "",
        planName: null,
        configId: null,
        configName: null,
        equipmentId: null,
        equipmentName: null,
        cycleType: "1",
        cycleValue: 1,
        cycleConfigJson: "",
        startDate: null,
        endDate: null,
        maintainerId: null,
        maintainerName: null,
        planStatus: "1",
        autoGenerate: "1",
        deptId: null,
        deptName: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.planId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.generatePlanCode();
      this.open = true;
      this.title = "添加保养计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const planId = row.planId || this.ids
      getMaintenancePlan(planId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改保养计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.planId != null) {
            updateMaintenancePlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaintenancePlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const planIds = row.planId || this.ids;
      this.$modal.confirm('是否确认删除保养计划编号为"' + planIds + '"的数据项？').then(function() {
        return deleteMaintenancePlan(planIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 生成保养记录操作 */
    handleGenerateRecord(row) {
      this.$modal.confirm('是否确认生成保养记录？').then(function() {
        return generateMaintenanceRecord(row.planId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("生成成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sb/maintenance/plan/export', {
        ...this.queryParams
      }, `maintenance_plan_${new Date().getTime()}.xlsx`)
    },
    // 生成计划编号
    generatePlanCode() {
      generatePlanCode().then(response => {
        this.form.planCode = response.data;
      });
    },
    // 设备选择变化
    handleEquipmentChange(equipmentId) {
      const equipment = this.equipmentOptions.find(item => item.equipmentId === equipmentId);
      if (equipment) {
        this.form.equipmentName = equipment.equipmentName;
      }
    },
    // 配置选择变化
    handleConfigChange(configId) {
      const config = this.configOptions.find(item => item.configId === configId);
      if (config) {
        this.form.configName = config.configName;
      }
    },
    // 保养人员选择变化
    handleMaintainerChange(maintainerId) {
      const user = this.userOptions.find(item => item.userId === maintainerId);
      if (user) {
        this.form.maintainerName = user.userName;
      }
    },
    // 部门选择变化
    handleDeptChange(deptId) {
      const dept = this.deptOptions.find(item => item.deptId === deptId);
      if (dept) {
        this.form.deptName = dept.deptName;
      }
    }
  }
};
</script> 